package br.net.woodstock.tickettoride.client.common;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Properties;

import br.net.woodstock.tickettoride.client.TicketConverter;
import br.net.woodstock.tickettoride.client.TicketException;
import br.net.woodstock.tickettoride.client.utils.CodecUtils;

public class PropertiesTicketConverter implements TicketConverter<Properties> {

	@Override
	public Properties fromBytes(final byte[] bytes) {
		try {
			InputStream inputStream = new ByteArrayInputStream(bytes);
			InputStreamReader reader = new InputStreamReader(inputStream, CodecUtils.CHARSET);
			Properties properties = new Properties();
			properties.load(reader);
			return properties;
		} catch (IOException e) {
			throw new TicketException(e);
		}
	}

	@Override
	public byte[] toBytes(final Properties t) {
		try {
			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
			OutputStreamWriter writer = new OutputStreamWriter(outputStream, CodecUtils.CHARSET);
			t.store(writer, null);
			return outputStream.toByteArray();
		} catch (IOException e) {
			throw new TicketException(e);
		}
	}

}
